import { createRouter, createWebHistory } from "vue-router";
import { useTokenStore } from "@/stores/token";
import { House, Menu, Document, User } from "@element-plus/icons-vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: () => import("@/views/Home.vue"),
      children: [
        {
          path: "/",
          name: "首页",
          icon: House,
          component: () => import("@/views/Index.vue"),
        },
        {
          path: "/category",
          name: "分类管理",
          icon: Menu,
          component: () => import("@/views/Category.vue"),
        },
        {
          path: "/product",
          name: "商品管理",
          icon: Document,
          component: () => import("@/views/Product.vue"),
        },
        {
          path: "/my",
          name: "个人中心",
          icon: User,
          component: () => import("@/views/My.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
  ],
});
router.beforeEach((to, from, next) => {
  const tokenStore = useTokenStore();
  if (to.name === "login" && tokenStore.token) {
    next({ name: "home" });
  } else if (to.name !== "login" && !tokenStore.token) {
    next({ name: "login" });
  } else {
    next();
  }
});
export default router;
